package com.jk.vehicle.core.controller;

import com.jk.vehicle.core.exception.LoginException;
import com.jk.vehicle.core.exception.ServiceException;
import com.jk.vehicle.core.constants.ResponseCode;
import com.jk.vehicle.core.constants.TokenConstants;
import com.jk.vehicle.core.entity.ResponseEntity;
import com.jk.vehicle.core.utils.TokenUtil;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局基础controller
 *
 * @author KangJian
 * @date 2018/07/19
 */
public class BaseController {

    /**
     * 管理员登录名
     */
    protected static final String SUPPER_ADMIN = "admin";


    /**
     * 默认返回信息
     */
    private static final String DEFAULT_SUCCESS_MESSAGE = "SUCCESS";

    /**
     * 成功返回
     *
     * @return
     */
    public ResponseEntity successResult() {
        return new ResponseEntity().setCode(ResponseCode.SUCCESS.code()).setMessage(DEFAULT_SUCCESS_MESSAGE);
    }

    /**
     * 成功返回
     *
     * @param data
     * @param <T>
     * @return
     */
    public <T> ResponseEntity<T> successResult(T data) {
        return new ResponseEntity().setCode(ResponseCode.SUCCESS.code()).setMessage(DEFAULT_SUCCESS_MESSAGE).setData(data);
    }

    /**
     * 失败返回
     *
     * @param message
     * @return
     */
    public ResponseEntity failResult(String message) {
        return new ResponseEntity().setCode(ResponseCode.FAIL.code()).setMessage(message);
    }

    /**
     * 校验是否是登陆并且管理员账号
     *
     * @param request
     * @return
     */
    protected boolean checkLoginAndAdmin(HttpServletRequest request) {
        String token = request.getHeader(TokenConstants.TOKEN_HEADER);
        try {
            if (TokenUtil.verifyToken(token).get(TokenConstants.LOGIN_NAME).asString().equals(SUPPER_ADMIN)) {
                // 在redis中清除已登陆
                return true;
            }
        } catch (Exception e) {
            throw new LoginException("token解析错误，请登陆获取token");
        }
        return false;
    }

    /**
     * 获取当前用户ID
     *
     * @param request
     * @return
     */
    protected String getLoginUserId(HttpServletRequest request) {
        String token = request.getHeader(TokenConstants.TOKEN_HEADER);
        try {
            return TokenUtil.verifyToken(token).get(TokenConstants.USE_ID).asString();
        } catch (Exception e) {
            throw new LoginException("token解析错误，请登陆获取token");
        }
    }

    /**
     * 获取当前用户名
     *
     * @param request
     * @return
     */
    protected String getLoginUserName(HttpServletRequest request) {
        String token = request.getHeader(TokenConstants.TOKEN_HEADER);
        try {
            return TokenUtil.verifyToken(token).get(TokenConstants.USER_NAME).asString();
        } catch (Exception e) {
            throw new LoginException("token解析错误，请登陆获取token");
        }
    }

    /**
     * 入参校验
     *
     * @param result
     * @throws ServiceException
     */
    protected void checkBindingResult(BindingResult result) throws ServiceException {
        if (result != null && result.getErrorCount() > 0) {
            String mess = "";
            for (ObjectError oe : result.getAllErrors()) {
                mess += oe.getDefaultMessage() + ";";
            }
            if (mess.endsWith(";")) {
                mess = mess.substring(0, mess.length() - 1);
                throw new ServiceException(mess);
            }
        }
    }

    protected ResponseEntity defaultFallBack() {
        return new ResponseEntity().setCode(
                HttpStatus.INTERNAL_SERVER_ERROR.value()).setMessage("系统发生异常");
    }
}
